<template>
  <div>
    <LocationComponent/>
      <van-icon name="arrow-left" @click="onClickLeft"/>
    <div id="map-container"></div>
    <van-tabbar style="top: 500px ;width: 100% ; height: 300px">
      <van-tabs v-model="active" style="width: 100%;">
        <van-tab title="现场维修">
          <van-card
              type="car"
              desc="北京市"
              title="北京市海淀区积云教育"
          >
            <template #footer>

              <van-button size="mini" @click="golocation">定位</van-button>
            </template>
          </van-card>
          <br>
          <van-card
             type="car"
              :desc="car.name"
          >
            <template #footer>

              <van-button size="mini" @click="updatesss">修改</van-button>
            </template>

          </van-card>
          <van-button type="info" @click="look">查看附近门店</van-button>
          <van-popup v-model="show" position="bottom" closeable :style="{ height: '30%' }" >
            <van-cell-group v-for="item in vehicles" :key="item.id">
              <van-card
                  desc=""
                  :title="item.name"
                  thumb="https://hh666.oss-cn-beijing.aliyuncs.com/ffb5bb8fa0fffa31a5a9fb05a0beaffb.jpeg"
                  @click=""
              >
                <template #tags>
                  <van-tag plain type="danger">{{ item.color }}</van-tag>
                  <van-tag plain type="danger">{{ item.brand }}</van-tag>
                  <van-tag plain type="danger">{{ item.type }}</van-tag>
                </template>

                <template #footer>
                  <van-button icon="delete-o" size="small" @click="findid(item.id)">选择</van-button>
                </template>
              </van-card>
            </van-cell-group>
          </van-popup>
        </van-tab>
        <van-tab title="预约维修" >

          <van-cell title="选择日期" :value="date" @click="time = true" />
          <van-calendar v-model="time" @confirm="onConfirm" />
          <br>
          <van-card
              type="car"
              :desc="car.name"
          >
            <template #footer>

              <van-button size="mini" @click="goupdate">修改</van-button>

            </template>

          </van-card>
          <van-button type="info" @click="look">查看附近门店</van-button>
          <van-popup v-model="hhh" position="bottom" closeable :style="{ height: '30%' }" >
            <van-cell-group v-for="item in vehicles" :key="item.id">
              <van-card
                  desc=""
                  :title="item.name"
                  thumb="https://hh666.oss-cn-beijing.aliyuncs.com/ffb5bb8fa0fffa31a5a9fb05a0beaffb.jpeg"
                  @click=""
              >
                <template #tags>
                  <van-tag plain type="danger">{{ item.color }}</van-tag>
                  <van-tag plain type="danger">{{ item.brand }}</van-tag>
                  <van-tag plain type="danger">{{ item.type }}</van-tag>
                </template>

                <template #footer>
                  <van-button icon="delete-o" size="small" @click="findid(item.id)">选择</van-button>
                </template>
              </van-card>
            </van-cell-group>
          </van-popup>
        </van-tab>

      </van-tabs>
    </van-tabbar>
  </div>
</template>

<script>
import LocationComponent from '../../components/container/MapContainer.vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import axios from 'axios';
import Vue from 'vue';
import { Form } from 'vant';
import { Field } from 'vant';
export default {
  components: {
    LocationComponent
  },
  data() {
    return {
      locationInfo: "", // 用于存储定位后的位置信息（可按需调整存储内容格式，比如对象等）
      map: null,
      pickedLngLat: '',
      longitude: '',
      latitude: '',
      address: null,
      loading: false,
      error: null,
      isFormOnTop: true,
      dialogTableVisible : true,
      formattedAddress:'',
      currentContact: {
        name: '',
        address: '',
      },
      car:{
        name:'',
      },
      currentDate:'',
      date: '',
      show: false,
      hhh:false,
      time: false,
      id:'',
    };
  },
  mounted() {
    // 1. 初始化地图
    this.initMap();
    // 2. 获取当前位置并在地图上标记展示，同时更新位置信息显示
    this.getCurrentPosition();
  },
  // mounted() {
  //   // 加载高德地图API
  //   AMapLoader.load({
  //     key: 'a373ee8b51caeb1973d221ef771f2e77',
  //     version: '2.0',
  //     plugins: ['AMap.Toolbar', 'AMap.Scale'] // 可按需添加插件
  //   }).then((AMap) => {
  //     // 创建地图实例
  //     this.map = new AMap.Map('map-container', {
  //       zoom: 50,
  //       center: [116.209128, 40.136332] // 设置地图初始中心点坐标，可根据实际需求调整
  //     });
  //     this.map.on('click', (e) => {
  //       this.pickedLngLat = e.lnglat.getLng() + ',' + e.lnglat.getLat();
  //     });
  //     // 添加地图工具栏
  //     new AMap.Toolbar().addTo(this.map);
  //
  //     // 添加地图比例尺
  //     new AMap.Scale().addTo(this.map);
  //   });
  //
  // },
  // beforeDestroy() {
  //   if (this.map) {
  //     this.map.destroy();
  //   }
  // },
methods: {
  initMap() {
    // 创建地图实例，设置相关属性
    this.map = new AMap.Map("mapContainer", {
      zoom: 13,
      center: [116.397428, 39.90923], // 初始地图中心坐标，可按需替换
      resizeEnable: true,
    });
  },
  getCurrentPosition() {
    // 先检查浏览器是否支持地理定位
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
          this.handlePositionSuccess,
          this.handlePositionError
      );
    } else {
      console.error("您的浏览器不支持地理定位");
    }
  },
  handlePositionSuccess(position) {
    const lng = position.coords.longitude;
    const lat = position.coords.latitude;
    // 在地图上标记当前位置
    const marker = new AMap.Marker({
      position: [lng, lat],
      map: this.map,
      title: "当前位置",
    });
    // 将地图中心设置为当前位置坐标
    this.map.setCenter([lng, lat]);
    // 获取地址信息（通过高德地图逆地理编码服务），更新位置信息显示
    this.getAddressByLocation(lng, lat);
  },
  handlePositionError(error) {
    console.error("获取位置信息出错：", error);
  },
  async getAddressByLocation(lng, lat) {
    // 假设在index.html中已全局引入高德地图脚本，挂载到window.AMap上
    if (window.AMap) {
      const geocoder = new window.AMap.Geocoder({});
      try {
        const res = await geocoder.getAddress([lng, lat]);
        if (res && res.regeocode && res.regeocode.formattedAddress) {
          this.locationInfo = res.regeocode.formattedAddress;
        } else {
          console.error("逆地理编码返回结果格式不正确");
        }
      } catch (e) {
        console.error("逆地理编码出错：", e);
      }
    } else {
      console.error("高德地图API未加载完成");
    }
  },

  findid(id){
    this.id=id;
    this.findId(id);
    this.show=false;
    this.hhh=false
  },
  findAll() {
    this.axios.get(`http://1.94.221.254:9999/api/qcfw-vehicles/vehicles/findAll`).then(res => {
      this.vehicles = res.data.data
    })
  },
  onSubmit(){
    this.hhh= false;
    this.show= false;
  },
  updatesss(){
    this.show = true;
  },
    look(){
      this.$router.push({ name: 'Shopping'})
    },

  findId(id){
    // var id =this.id
   this.axios.get(`http://1.94.221.254:9999/api/qcfw-vehicles/vehicles/findId/${id}`).then(res => {
      this.car=res.data.data
      console.log("找到的"+res.data)
   })
  },
  findOne() {
    this.axios.get(`http://1.94.221.254:9999/api/qcfw-vehicles/vehicles/findOne`).then(res => {
      console.log("找到的"+res.data.data)
      this.car = res.data.data
    })
  },

  formatDate(date) {
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  onConfirm(date) {
    this.show = true;
    this.date = this.formatDate(date);
  },
  markLocationOnMap() {
    const marker = new AMap.Marker({
      position: [this.longitude, this.latitude],
      map: this.map
      // 可以添加自定义样式等
    });
    console.log("fsafda"+this.longitude)
    console.log("fsafda"+this.longitude)

    // 可添加信息窗口等更多功能，这里暂未添加
  },

  goupdate(){
    this.hhh = true;
  },
  golocation() {
    // 链接后台定位接口实现定位之后将值传入pickedLngLat
    // this.pickedLngLat=""
    this.$message.success('定位成功');
  },
  onClickLeft(){
    this.$router.push({ name: 'shouye', params: { id: this.token }})
  },

  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  }
},
  created() {
    this.findAll();
    this.findOne();
    this.beforeDestroy();
    this.markLocationOnMap();
    this.sendLocationToBackend();
    var token = localStorage.getItem('token');
    if (token === null) {
      this.$router.push('/');
    }
  }
};
</script>

<style>
#map-container {
  width: 100%;
  height: 900px; /* 可根据需求设置地图容器高度 */
}

html, body {
  width: 100%;
  height: 100%;
  margin: 0px;
}

.map {
  width: 100%;
  height: 100%;
  float: left;
}

.input-card {
  margin-top: 10px;
}

.input-item {
  margin-top: 5px;
}

</style>
